// 导入 React
import { useState, useEffect } from 'react'
// 路由
import { useNavigate } from 'react-router-dom'
// 导入API接口
import { 
  getServicesByTab, 
  getHealthInfo,
  type OutpatientService,
  type InpatientService,
  type ComprehensiveService,
  type HealthInfo
} from '../../api/outpatient'
// 样式
import './index.css'

function Index() {
  // 为后续点击跳转预留（当前静态页暂未调用）
  const navigate = useNavigate()



  // 页面中部大轮播图（按你的截图样式）
  const carouselImages = [
    'https://images.unsplash.com/photo-1583324113626-70df0f4deaab?w=1600&q=80&auto=format&fit=crop',
    'https://images.unsplash.com/photo-1584982751601-97dcc096659c?w=1600&q=80&auto=format&fit=crop',
    'https://images.unsplash.com/photo-1582719478250-c89cae4dc85b?w=1600&q=80&auto=format&fit=crop',
    'https://images.unsplash.com/photo-1587854692152-cbe660dbde88?w=1600&q=80&auto=format&fit=crop'
  ]
  const [carouselIndex, setCarouselIndex] = useState(0)
  useEffect(() => {
    const t = setInterval(() => {
      setCarouselIndex((prev) => (prev + 1) % carouselImages.length)
    }, 3500)
    return () => clearInterval(t)
  }, [carouselImages.length])

  // 门诊/住院/综合 tabs 状态管理
  const [activeBizTab, setActiveBizTab] = useState(0)
  const [loading, setLoading] = useState(false)
  const [services, setServices] = useState<(OutpatientService | InpatientService | ComprehensiveService)[]>([])
  
  const bizTabs = [
    { key: 'outpatient', name: '门诊' },
    { key: 'inpatient', name: '住院' },
    { key: 'comprehensive', name: '综合' }
  ]

  // 健康资讯状态
  const [healthInfos, setHealthInfos] = useState<HealthInfo[]>([])

  // 加载服务数据（首页只显示前8个）
  const loadServices = async (tabType: 'outpatient' | 'inpatient' | 'comprehensive') => {
    setLoading(true)
    try {
      const data = await getServicesByTab(tabType)
      // 首页只显示前8个服务项目
      setServices(data.slice(0, 8))
    } catch (error) {
      console.error('加载服务数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  // 加载健康资讯（首页只显示前3篇）
  const loadHealthInfo = async () => {
    try {
      const data = await getHealthInfo()
      // 首页只显示前3篇健康资讯
      setHealthInfos(data.slice(0, 3))
    } catch (error) {
      console.error('加载健康资讯失败:', error)
    }
  }

  // 初始化数据
  useEffect(() => {
    loadServices('outpatient')
    loadHealthInfo()
  }, [])

  // 处理tab切换
  const handleTabChange = (index: number) => {
    setActiveBizTab(index)
    const tabType = bizTabs[index].key as 'outpatient' | 'inpatient' | 'comprehensive'
    loadServices(tabType)
  }

  // 处理服务项点击
  const handleServiceClick = (service: OutpatientService | InpatientService | ComprehensiveService) => {
    if (service.route) {
      navigate(service.route)
    } else {
      console.log('点击服务:', service.name)
      // 这里可以添加其他处理逻辑
    }
  }

  // 生成渐变背景色
  const generateGradientColors = (serviceId: number) => {
    const colors = [
      { from: '#e8f3ff', to: '#d4e7ff' },
      { from: '#e9f7ef', to: '#d3f0e0' },
      { from: '#fff2e8', to: '#ffe1cc' },
      { from: '#f2ecff', to: '#e4dbff' },
      { from: '#e8f7ff', to: '#d6eeff' },
      { from: '#fff0f5', to: '#ffd9e6' },
      { from: '#eff8ff', to: '#d9edff' },
      { from: '#f3ffe9', to: '#e2ffd0' }
    ]
    return colors[serviceId % colors.length]
  }

  return (
    <div>
      <>
        {/* 顶部导航 + Banner 卡片（贴合参考图） */}
        <div style={{ padding: '10px 12px 0 12px' }}>
          {/* 导航栏 */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', height: 44 }}>
            <div style={{ fontSize: 18, fontWeight: 900, color: '#1f2d3d' }}>智慧医院平台</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, color: '#94a3b8' }}>
              <span style={{ fontSize: 22, lineHeight: 1 }}>⋯</span>
              <span style={{ fontSize: 18 }}>◁</span>
            </div>
          </div>

          {/* Banner 卡片 */}
          <div style={{
            marginTop: 8,
            background: 'linear-gradient(135deg,#27c1c3,#1aa2f1)',
            color: '#fff',
            borderRadius: 16,
            padding: 16,
            boxShadow: '0 12px 28px rgba(26,162,241,0.25)'
          }}>
            <div style={{ fontSize: 28, fontWeight: 900, lineHeight: 1.15 }}>智慧医院
              <br />理赔无忧
            </div>
            <div style={{ display: 'flex', gap: 12, marginTop: 12 }}>
              {['🤖','📱','🔔','🔒'].map((g,i)=> (
                <div key={i} style={{ width: 42, height: 42, borderRadius: 12, background: 'rgba(255,255,255,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.22)' }}>{g}</div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
              <div style={{ width: 24, height: 4, borderRadius: 4, background: '#fff' }} />
              <div style={{ width: 6, height: 4, borderRadius: 4, background: 'rgba(255,255,255,0.6)' }} />
            </div>
          </div>
        </div>

        {/* 中部大轮播图 */}
        <div style={{ padding: '0 12px' }}>
          <div style={{ position: 'relative', height: 140, marginTop: 12, borderRadius: 18, overflow: 'hidden', boxShadow: '0 10px 24px rgba(0,0,0,0.08)' }}>
            <div style={{
              width: '100%', height: '100%',
              backgroundImage: `url(${carouselImages[carouselIndex]})`,
              backgroundSize: 'cover', backgroundPosition: 'center'
            }} />
            <div style={{ position: 'absolute', left: '50%', bottom: 8, transform: 'translateX(-50%)', display: 'flex', flexDirection: 'row', gap: 8 }}>
              {carouselImages.map((_, i) => (
                <div key={i} style={{ width: 8, height: 8, borderRadius: 10, background: i === carouselIndex ? '#3b82f6' : 'rgba(255,255,255,0.9)', boxShadow: '0 0 2px rgba(0,0,0,0.2)' }} />
              ))}
            </div>
          </div>
        </div>

        {/* 两张大卡片：门诊挂号 / 门诊缴费 */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 12, padding: '0 12px' }}>
          <div 
            style={{ 
              background: 'linear-gradient(135deg,#3da9ff,#7dccff)', 
              borderRadius: 12, 
              padding: 16, 
              color: '#fff',
              cursor: 'pointer',
              transition: 'transform 0.2s ease'
            }}
            onClick={() => navigate('/appointment-notice')}
            onMouseEnter={(e) => {
              e.currentTarget.style.transform = 'scale(1.02)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = 'scale(1)'
            }}
          >
            <div style={{ fontSize: 18, fontWeight: 700 }}>门诊挂号</div>
            <div style={{ opacity: 0.9, marginTop: 6 }}>便捷预约挂号</div>
          </div>
          <div 
            style={{ 
              background: 'linear-gradient(135deg,#35c3a8,#7ae3cf)', 
              borderRadius: 12, 
              padding: 16, 
              color: '#fff',
              cursor: 'pointer',
              transition: 'transform 0.2s ease'
            }}
            onClick={() => navigate('/outpatient-payment')}
            onMouseEnter={(e) => {
              e.currentTarget.style.transform = 'scale(1.02)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = 'scale(1)'
            }}
          >
            <div style={{ fontSize: 18, fontWeight: 700 }}>门诊缴费</div>
            <div style={{ opacity: 0.9, marginTop: 6 }}>便捷预约挂号</div>
          </div>
        </div>

        {/* 公告栏 */}
        <div 
          style={{ 
            marginTop: 12, 
            padding: '10px 12px', 
            background: '#fff', 
            borderRadius: 12, 
            boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
            cursor: 'pointer',
            transition: 'all 0.2s ease'
          }}
          onClick={() => navigate('/hospital-announcement')}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = 'translateY(-1px)'
            e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)'
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'translateY(0)'
            e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.06)'
          }}
        >
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ fontWeight: 700, marginRight: 10 }}>公告</span>
            <span style={{ color: '#666', flex: 1 }}>智慧医院即将上线通知</span>
            <span style={{ color: '#bbb' }}>›</span>
          </div>
        </div>

        {/* Tabs + 功能网格（动态数据） */}
        <div style={{ marginTop: 10, padding: 12, background: '#fff', borderRadius: 12, boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
            {bizTabs.map((tab, idx) => (
              <div
                key={idx}
                onClick={() => handleTabChange(idx)}
                style={{
                  padding: '6px 10px',
                  borderRadius: 999,
                  fontSize: 14,
                  marginRight: 10,
                  color: activeBizTab === idx ? '#1677ff' : '#666',
                  background: activeBizTab === idx ? 'rgba(22,119,255,0.1)' : 'transparent',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease'
                }}
              >
                {tab.name}
              </div>
            ))}
            <div 
              style={{ marginLeft: 'auto', color: '#999', cursor: 'pointer' }}
              onClick={() => navigate(`/more-services?tab=${bizTabs[activeBizTab].key}`)}
            >
              更多
            </div>
          </div>
          
          {/* 加载状态 */}
          {loading && (
            <div style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
              加载中...
            </div>
          )}
          
          {/* 服务网格 */}
          {!loading && (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
              {services.map((service) => {
                const colors = generateGradientColors(service.id)
                return (
                  <div 
                    key={service.id} 
                    style={{ 
                      display: 'flex', 
                      alignItems: 'center', 
                      flexDirection: 'column',
                      cursor: 'pointer',
                      transition: 'transform 0.2s ease'
                    }}
                    onClick={() => handleServiceClick(service)}
                    onMouseEnter={(e) => {
                      e.currentTarget.style.transform = 'translateY(-2px)'
                    }}
                    onMouseLeave={(e) => {
                      e.currentTarget.style.transform = 'translateY(0)'
                    }}
                  >
                    <div style={{
                      width: 56,
                      height: 56,
                      borderRadius: 12,
                      marginBottom: 8,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      background: `linear-gradient(135deg, ${colors.from}, ${colors.to})`,
                      boxShadow: '0 2px 10px rgba(93,110,180,0.08)'
                    }}>
                      <span style={{ fontSize: 24 }}>{service.icon}</span>
                    </div>
                    <div style={{ 
                      fontSize: 12, 
                      textAlign: 'center',
                      lineHeight: 1.2,
                      color: '#333'
                    }}>
                      {service.name}
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </div>

        {/* 健康资讯（动态数据） */}
        <div style={{ marginTop: 10, padding: 12, background: '#fff', borderRadius: 12, boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 16, fontWeight: 700 }}>健康资讯</span>
            <span 
              style={{ color: '#999', cursor: 'pointer' }}
              onClick={() => navigate('/health-info')}
            >
              更多
            </span>
          </div>
          <div style={{ height: 8 }} />
          {healthInfos.map(info => (
            <div key={info.id} style={{ 
              background: '#f6f8ff', 
              borderRadius: 12, 
              padding: 12, 
              marginBottom: 12,
              cursor: 'pointer',
              transition: 'all 0.2s ease'
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.transform = 'translateY(-1px)'
              e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.1)'
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.transform = 'translateY(0)'
              e.currentTarget.style.boxShadow = 'none'
            }}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 16, fontWeight: 700, lineHeight: 1.4 }}>{info.title}</div>
                  {info.summary && (
                    <div style={{ 
                      fontSize: 12, 
                      color: '#666', 
                      marginTop: 4,
                      lineHeight: 1.3,
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical',
                      overflow: 'hidden'
                    }}>
                      {info.summary}
                    </div>
                  )}
                </div>
                <img src={info.cover} alt={info.title} style={{ width: 80, height: 64, borderRadius: 10, objectFit: 'cover' }} />
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8, color: '#6b7aff' }}>
                <span style={{ fontSize: 12 }}>{info.tag}</span>
                <div style={{ color: '#8390a3', fontSize: 12 }}>
                  <span style={{ marginRight: 16 }}>👍 {info.likes}</span>
                  <span>👁️ {info.views}</span>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* 浮动客服按钮 */}
        <div 
          style={{ 
            position: 'fixed', 
            right: 16, 
            bottom: 92, 
            width: 64, 
            height: 64, 
            background: '#2b7cff', 
            color: '#fff', 
            borderRadius: 9999, 
            display: 'flex', 
            alignItems: 'center', 
            justifyContent: 'center', 
            boxShadow: '0 6px 18px rgba(43,124,255,0.35)', 
            cursor: 'pointer',
            fontSize: '12px',
            fontWeight: '500',
            transition: 'all 0.2s ease'
          }}
          onClick={() => navigate('/message')}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = 'scale(1.05)'
            e.currentTarget.style.boxShadow = '0 8px 24px rgba(43,124,255,0.45)'
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'scale(1)'
            e.currentTarget.style.boxShadow = '0 6px 18px rgba(43,124,255,0.35)'
          }}
        >
          智能客服
        </div>

        {/* 底部 TabBar（纯排版） */}
        <div style={{ position: 'fixed', left: 0, right: 0, bottom: 0, borderTop: '1px solid #eee', background: '#fff', height: 56, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)' }}>
          {[
            { key: 'home', title: '诊疗首页', icon: '🏠' },
            { key: 'web', title: '微官网', icon: '🌐' },
            { key: 'msg', title: '消息中心', icon: '💬' },
            { key: 'me', title: '我的', icon: '👤' },
          ].map((i) => (
            <div key={i.key} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontSize: 12, color: i.key === 'home' ? '#1677ff' : '#666' }}>
              <div style={{ fontSize: 18, marginBottom: 2 }}>{i.icon}</div>
              <div>{i.title}</div>
            </div>
          ))}
        </div>
      
      </>
    </div>
  )
}

export default Index


